package com.tianqu.tms.www.finance.controller;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.PullingExecutor;
import com.tianqu.tms.core.webservice.weichat.api.rpc.IntegralRegisterBo;
import com.tianqu.tms.entity.Attn;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.IntegralRegister;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.entity.Sequence;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.entity.TransferFinanceInfo;
import com.tianqu.tms.entity.TransferPersonalCarInfo;
import com.tianqu.tms.entity.TransferProcessHistory;
import com.tianqu.tms.www.finance.actionform.CarProxyPaySearchInputForm;
import com.tianqu.tms.www.finance.viewhelper.CarProxyPaySearchInputViewHelper;

public class CarProxyRetreatTransAccInputController extends TmsController {
	private Logger logger = Logger.getLogger(CarProxyRetreatTransAccInputController.class);

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();
		Sequence seq = Sequence.getInstance();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			CarProxyPaySearchInputForm inputForm = (CarProxyPaySearchInputForm) uc.getInputForm();
			TmsUserProfile profile = uc.getUserProfile();
			String serial = inputForm.getSerial();
			String price = inputForm.getRealAmount();
//			if(inputForm.getTransferPriceChargeType() == 2)
//			{
//				price = inputForm.getCardScore();
//			}
			CarProxyPaySearchInputViewHelper viewhelper = new CarProxyPaySearchInputViewHelper();
			TransferAcceptedInfo accept = new TransferAcceptedInfo();
			accept = accept.getAcceptInfoBySerial(serial,"");
			TransferFinanceInfo finance = new TransferFinanceInfo();
			finance = finance.findFinanceInfoByserial(serial);
			TransferProcessHistory process = new TransferProcessHistory();

			int tbstatus = 21;
			//库存 or 非库存
			//如果车辆是库存车辆
			if(accept.getMarketType() == 1)
			{
				Car car = new Car();
				car = car.findCarBySerial(accept.getBasicCarId());
				//modify by huangheli at 20151016 start
				car.setStatus(1);
//				car.setStatus(4);
//				car.setRegisterStatus(4);
				//modify by huangheli at 20151016 end
				car.setUpdateUserId(profile.getUniqueId());
				car.updateMarketCarInfo(car);
//				workload:3.1.2 delete
//				//1）如果是库存车辆：
//				bo1.setStatus(1);
//				bo1.setDetailStatus(0);
			}
			//如果车辆是非库存车辆
			if(accept.getMarketType() == 2)
			{
				TransferPersonalCarInfo person = new TransferPersonalCarInfo();
				person = person.getPersonalCarInfoBySerial(accept.getBasicCarId());
				person.setStatus(4);
				person.setUpdateUserId(profile.getUniqueId());
				person.updateCarBaseInfo(person);
//				workload:3.1.2 delete
//				//2）如果是非库存车辆：
//				bo1.setStatus(16);
//				if(accept.getStatus() == 21){
//					bo1.setDetailStatus(21);
//				}
//				if(accept.getStatus() == 22){
//					bo1.setDetailStatus(36);
//				}
//				if(accept.getStatus() == 26||(accept.getLc_printTime()!=null&&finance.getTransferPriceDate()!=null&&accept.getZy_printTime()==null))
//				{
//					bo1.setDetailStatus(26);
//				}
			}
			if(accept.getStatus() == 21)
			{
				tbstatus = 21;
				finance.setSdBackPrice(Integer.parseInt(StringUtil.removeDH(price)));
				

			}
			if(accept.getStatus() == 22)
			{
				tbstatus = 36;
				finance.setPzBackPrice(Integer.parseInt(StringUtil.removeDH(price)));
				
			}
			if(accept.getStatus() == 26||(accept.getLc_printTime()!=null&&finance.getTransferPriceDate()!=null&&accept.getZy_printTime()==null))
			{
				tbstatus = 26;
				finance.setOtherBackPrice(Integer.parseInt(StringUtil.removeDH(price)));
				
			}
			//过户
			accept.setStatus(16);
			accept.setUpdateUserId(profile.getUniqueId());
			TransferAcceptedInfo accept1 = new TransferAcceptedInfo();
			accept1 = accept1.getAcceptInfoBySerial(serial,"");
			accept.setChangeTradeTicket(accept1.getChangeTradeTicket());
			accept.updateAcceptStatusBySerial(accept);
			
			//workload:3.1.2
//			//add by huangheli at 20151016 start
//			//插入 过户业务基本信息表（tms_transfer_accepted_info）
//			String transferSerial = seq.getSerial(6);
//			TransferAcceptedInfo transferAcceptedInfo = TransferAcceptedInfo.getInstance();
//			transferAcceptedInfo.setSerial(transferSerial);
//			transferAcceptedInfo.setMarketType(1);
//			transferAcceptedInfo.setCarClass(2);
//			transferAcceptedInfo.setStatus(0);
//			transferAcceptedInfo.setSourceType(1);
//			transferAcceptedInfo.setLicensePlate(accept.getLicensePlate());
//			transferAcceptedInfo.setBasicCarId(accept.getBasicCarId());
//			transferAcceptedInfo.setMemberId(accept.getMemberId());
//			transferAcceptedInfo.setInsertUserid(profile.getUniqueId());
//			transferAcceptedInfo.setUpdateUserId(profile.getUniqueId());
//			transferAcceptedInfo.insertCarResumeInfo(transferAcceptedInfo);
//			//add by huangheli at 20151016 end
			
			
			//财务
			finance.setSerial(serial);
			finance.setBackChargeType(1);
			finance.updateFinanceInfoPrice(finance);
			TransferFinanceInfo ff = new TransferFinanceInfo();
			ff.setSerial(serial);
			ff.setBackPriceUserId(profile.getUniqueId());
			ff.updateBackPriceDate(ff);
			//历史记录
			process.setSerial(serial);
			process.setBusinessType(tbstatus);
			process.setInsertUserId(profile.getUniqueId());
			process.insertHisInfoAtAssess(process);
			
			// add by huangheli 2016/01/09 start
			MobileMessage message1 = new MobileMessage();
			message1.putValue("Serial", serial);
			message1.setMessage("财务模块[过户收费]接口,过户流水号为#Serial#过户信息不存在，无法同步TMS的退办退费");

			IntegralRegister reg = new IntegralRegister();
			reg = reg.getIntegralRegisterInfoBySerial(serial, 2, 1);
			if(reg!=null)
			{
				if(reg.getMemberType() == 1)
				{
					Member member = new Member();
					member = member.findCarScoreByMemberId(reg.getMemberId());
					//modify by huangheli at 20151012 start
					//String wp = String.valueOf(Integer.parseInt(StringUtil.removeDH(price)) * Double.parseDouble(Registry.getConfig(TmsConstants.WWW_JIFEN_MEMBER_KEY)));
					String wp = String.valueOf(Integer.parseInt(StringUtil.removeDH(price)) * member.getIntegralRatio());
					//modify by huangheli at 20151012 end
					if(wp.indexOf(".")!=-1)
					{
						wp = wp.substring(0, wp.indexOf("."));
					}
					if(member.getCardScore()-Integer.parseInt(wp) < 0){
						viewhelper.setBackFlag(2);
						member.setCardScore(0);
						reg.setIntegral(Integer.parseInt(wp) - member.getCardScore());
					}else{
						member.setCardScore(member.getCardScore()-Integer.parseInt(wp));
						reg.setIntegral(Integer.parseInt(wp));
					}					
					member.setMemId(Integer.parseInt(reg.getMemberId()));
					member.setUpdateUserId(profile.getUniqueId());
					member.updateIntegralCardScore(member);
				}
				if(reg.getMemberType() == 2)
				{
					Attn attn = new Attn();
					attn = attn.findAttnByAttnId(reg.getMemberId());
					//modify by huangheli at 20151012 start
					//String ep = String.valueOf(Integer.parseInt(StringUtil.removeDH(price)) * Double.parseDouble(Registry.getConfig(TmsConstants.WWW_JIFEN_ATTN_KEY)));
					String ep = String.valueOf(Integer.parseInt(StringUtil.removeDH(price)) * attn.getIntegralRatio());
					//modify by huangheli at 20151012 end
					if(ep.indexOf(".")!=-1)
					{
						ep = ep.substring(0, ep.indexOf("."));
					}
					if(attn.getCardScore() - Integer.parseInt(ep) < 0){
						viewhelper.setBackFlag(2);
						attn.setCardScore(0);
						reg.setIntegral(Integer.parseInt(ep) - attn.getCardScore());
					}else{
						attn.setCardScore(attn.getCardScore()-Integer.parseInt(ep));
						reg.setIntegral(Integer.parseInt(ep));
					}
					attn.setAttnId(reg.getMemberId());
					attn.setUpdateUserId(profile.getUniqueId());
					attn.updateIntegralCardScore(attn);
				}
				
				reg.setMemberId(reg.getMemberId());
				reg.setMemberType(reg.getMemberType());
				reg.setSerial(serial);
				reg.setLicensePlate(reg.getLicensePlate());
				reg.setTransferPrice(Integer.parseInt(StringUtil.removeDH(price)));
				reg.setInsertUserId(profile.getUniqueId());
				reg.setPlusMinus(2);
				reg.setChargeType(4);
				reg.setIntegral(reg.getIntegral());	
				if(viewhelper.getBackFlag() ==2){
					reg.setRemark("【会员积分不足】，请联系管理员处理!");
				}
				reg.insertRegisterInfo(reg);
				//add by huangheli at 20151019 start
				//通过API接口将录入信息传送给车代办平台
				MobileMessage message = new MobileMessage();
				message.putValue("LicensePlate", reg.getLicensePlate());
				message.putValue("MemberId", reg.getMemberId());
				message.setMessage("无法同步[过户退费]接口,商户ID为#MemberId#,车牌号为#LicensePlate#");
				IntegralRegisterBo m = new IntegralRegisterBo();
				m.setMobileMessage(message);
				m.setChargeType(4);
				m.setIntegral(reg.getIntegral());
				m.setLicensePlate(reg.getLicensePlate());
				m.setMemberId(reg.getMemberId());
				m.setMemberType(reg.getMemberType());
				m.setSerial(reg.getSerial());
				m.setTransferPrice(reg.getTransferPrice());
				PullingExecutor.getInstance().submit(m);
				//add by huangheli at 20151019 end		
				
				uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			}

			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				try {
					throw e;
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");

	}

}
